<script setup>
import { h, onMounted, ref, resolveDirective, withDirectives } from 'vue'
import {
  NForm,
  NFormItem,
  NInput,
  NInputNumber,
  NFlex,
} from 'naive-ui'

import CommonPage from '@/components/page/CommonPage.vue'
import { getToken } from '@/utils'
import { useCRUD } from '@/composables'
import api from '@/api'
import {useRoute} from "vue-router"
import {TRUE} from "sass";
import {router} from "@/router";
const route = useRoute()


import * as ydui from '@/assets/js/ydui.citys';
import {useTagsStore} from "@/store";
const tagsStore = useTagsStore()
let yduiCtiys = YDUI_CITYS;
let addressArr = reactive({ options: [] });
let addrs = [];
yduiCtiys.forEach((province, pid) =>{
    let p = {};
    p.label = province.n;
    p.id = province.n
    // p.children = province.c;
    addrs.push(p)

    addrs[pid].children = [];
    province.c.forEach((city, cid) => {
        let c = {};
        c.label = city.n;
        c.id = `${province.n} ${city.n}`
        addrs[pid].children.push(c)

        c.children = []

        city.a.forEach((area, aid) => {
            let a = {};
            a.label = area;
            a.id = `${province.n} ${city.n} ${area}`
            c.children.push(a)
        })

    })
})
addressArr.options = addrs


defineOptions({ name: '运费模版编辑' })

const $table = ref(null)
const queryItems = ref({})
const vPermission = resolveDirective('permission')
const base_path = import.meta.env.VITE_BASE

const {
  modalVisible,
  modalTitle,
  modalLoading,
  modalForm,
  modalFormRef,
  handleEdit,
  handleDelete,
  handleAdd,
  handleSave,
} = useCRUD({
  name: '运费模版',
  initForm: {},
  doCreate: api.creategoodsExpress,
  doUpdate: api.updategoodsExpress,
  doDelete: api.deletegoodsExpress,
  refresh: () => $table.value?.handlerefresh(),
})

const data = reactive({
  songsData: [
    {
      value: 1,
      label: '按重量(千克)',
    },
    {
      value: 2,
      label: '按件数',
    },
  ],
  token: getToken(),
  row:[]
})
const onCreate = () => {
  return {
    address: '',
    frist: '',
    frist_price: '',
    next: '',
    next_price: '',
  }
}
const onCreateStop = () => {
  return {
    stop_address: '',
    begin_time: null,
    end_time: null,
  }
}

function on_save(){
  handleSave()

}

async function get_data(id) {
  let ret =await api.detailgoodsExpress({data_id:id})
  data.row = ret.data
  handleEdit(data.row)
}
function on_list(){
  tagsStore.removeTag(route.fullPath)
  router.push("/goods/express")
}

onMounted(() => {
  const id = route.query.id
  modalVisible.value = true
  if(id>0){
    get_data(id)
  }else{
    handleAdd()
  }
  $table.value?.handleSearch()
})

watch(modalVisible, (newValue, oldValue) => {
  if(!modalVisible.value){
    tagsStore.removeTag(route.fullPath)
    router.push("/goods/express")
  }
});

const validateAddUser = {
    name: [
        {
            required: true,
            message: '请输入模板名称',
            trigger: ['input', 'blur', 'change'],
        },
    ],
}
</script>

<template >
  <!-- 业务页面 -->
  <CommonPage show-footer title="编辑运费模板" >
    <NForm
      ref="modalFormRef"
      label-placement="left"
      label-align="left"
      :label-width="80"
      :model="modalForm"
      :rules="validateAddUser"
    >
      <n-card content-style="padding: 0;" >
        <n-tabs type="line" animated size="large" :tabs-padding="20" pane-style="padding: 20px;">
          <n-tab-pane name="基础信息" >
            <NFlex justify="space-between">
              <NFormItem label="模板名称" path="name" style="width: 100%">
                <NInput v-model:value="modalForm.name" clearable placeholder="请输入模板名称" />
              </NFormItem>
              <NFormItem label="计价方式" path="type" style="width: 100%">
                <n-radio-group v-model:value="modalForm.type" name="radiogroup" :default-value="1">
                  <n-space>
                    <n-radio v-for="song in data.songsData" :key="song.value" :value="song.value">
                      {{ song.label }}
                    </n-radio>
                  </n-space>
                </n-radio-group>
              </NFormItem>
              <NFormItem label="区域规则" path="roles">
                 <n-layout>
                  <n-layout-header>
                    <n-flex v-if="modalForm.type==2">
                      <n-tag size="large" style="width: 200px"> 区域 </n-tag>
                      <n-tag size="large" style="width: 100px;"> 首件 </n-tag>
                      <n-tag size="large" style="width: 100px;"> 首件价格 </n-tag>
                      <n-tag size="large" style="width: 100px;"> 续件 </n-tag>
                      <n-tag size="large" style="width: 100px"> 续件价格 </n-tag>
                    </n-flex>
                    <n-flex v-else>
                      <n-tag size="large" style="width: 200px"> 区域 </n-tag>
                      <n-tag size="large" style="width: 100px;"> 首重 </n-tag>
                      <n-tag size="large" style="width: 100px;"> 首重价格 </n-tag>
                      <n-tag size="large" style="width: 100px;"> 续重 </n-tag>
                      <n-tag size="large" style="width: 100px"> 续重价格 </n-tag>
                    </n-flex>
                  </n-layout-header>
                  <n-layout-content content-style="padding: 10px 0;">
                    <n-dynamic-input v-model:value="modalForm.roles" :on-create="onCreate" >
                              <template #default="{ value }">
                                <n-flex justify="space-between">
                                    <n-cascader
                                       v-model:value="value.address"
                                       clearable
                                       separator=" "
                                       placeholder="请选择区域"
                                       expand-trigger="click"
                                       :options="addressArr.options"
                                       label-field="label"
                                       value-field="id"
                                       children-field="children"
                                       style="width: 200px"
                                        >
                                  </n-cascader>
                                  <n-input-number button-placement="both"
                                    v-model:value="value.frist"
                                    style="width: 100px"
                                    min="1"
                                  />
                                  <n-input-number :show-button="false"
                                    v-model:value="value.frist_price"
                                    style="width: 100px"
                                  >
                                    <template #prefix> ￥ </template>
                                  </n-input-number>
                                  <n-input-number button-placement="both"
                                    v-model:value="value.next"
                                    style="width: 100px"
                                    min="1"
                                  />

                                  <n-input-number :show-button="false"
                                    v-model:value="value.next_price"
                                    style="width: 100px"
                                  >
                                    <template #prefix> ￥ </template>
                                  </n-input-number>
                                </n-flex>
                              </template>
                            </n-dynamic-input>
                  </n-layout-content>
                </n-layout>
              </NFormItem>
            </NFlex>
          </n-tab-pane>
          <n-tab-pane name="停发区域">
            <NFormItem label="地区" path="stop_roles">
              <n-layout>
                  <n-layout-header>
                    <n-flex>
                      <n-tag size="large" style="width: 200px"> 停发区域 </n-tag>
                      <n-tag size="large" style="width: 160px;"> 开始时间 </n-tag>
                      <n-tag size="large" style="width: 160px;"> 结束时间 </n-tag>
                    </n-flex>
                  </n-layout-header>
                  <n-layout-content content-style="padding: 10px 0;">
                    <n-dynamic-input v-model:value="modalForm.stop_roles" :on-create="onCreateStop">
                      <template #default="{ value }">
                        <n-flex justify="space-between">
                          <n-cascader
                                 v-model:value="value.stop_address"
                                 clearable
                                 separator=" "
                                 placeholder="请选择区域"
                                 expand-trigger="click"
                                 :options="addressArr.options"
                                 label-field="label"
                                 value-field="id"
                                 children-field="children"
                                 style="width: 200px"
                                 >
                            </n-cascader>
                          <n-date-picker  style="width: 160px" type="date" v-model:formatted-value="value.begin_time"  value-format="yyyy-MM-dd" placeholder="开始时间" />
                          <n-date-picker  style="width: 160px" type="date" v-model:formatted-value="value.end_time"  value-format="yyyy-MM-dd" placeholder="结束时间" />
                        </n-flex>
                      </template>
                    </n-dynamic-input>
                  </n-layout-content>
              </n-layout>

            </NFormItem>
          </n-tab-pane>
        </n-tabs>
      </n-card>
      <n-button :loading="loading" mt-20 type="primary" @click="on_list">返回列表</n-button>
      <n-button :loading="loading" mt-20 ml-15 type="primary" @click="on_save">保存</n-button>
    </NForm>
  </CommonPage>
</template>
